﻿using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.Linq;
using yiCommerce.Core;
using yiCommerce.Core.Data;

namespace yiCommerce.Data
{
    public class MongoRepository<T> : IMongoRepository<T> where T : BaseMongoEntity
    {
        private MongoDatabase database;

        public MongoRepository()
        {
            var connectionString = "mongodb://localhost";
            var client = new MongoClient(connectionString);
            var server = client.GetServer();
            database = server.GetDatabase("yiCommerce");
        }

        public T GetById(string entityName, ObjectId id)
        {
            var query = Query<T>.EQ(e => e.Id, id);

            var collection = database.GetCollection<T>(entityName);

            var entity = collection.FindOne(query);
            return entity;
        }

        public ObjectId Insert(string entityName, T entity)
        {
            //var entityname = typeof (T).Name;
            var collection = database.GetCollection<T>(entityName);
            collection.Insert(entity);
            var id = entity.Id;
            return id;

        }

        public void Update(T entity)
        {
            throw new System.NotImplementedException();
        }

        public void Delete(T entity)
        {
            throw new System.NotImplementedException();
        }

        public IQueryable<T> Table(string entityName)
        {
            return database.GetCollection<T>(entityName).AsQueryable<T>();
        }
    }
}
